package com.captain.special.字符串;

import java.util.ArrayList;
import java.util.List;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/4/5 17:05
 */
public class 翻转字符串里的单词151 {
    public static void main(String[] args) {
        System.out.println(new 翻转字符串里的单词151().reverseWords("a good   example"));
    }

    public String reverseWords(String s) {
        List<String> list = new ArrayList<>(s.length());
        int left = 0;
        char[] chars = s.toCharArray();
        char last = 0;
        for (int i = 0; i < chars.length; i++) {
            char val = chars[i];
            if (val == ' ' && last != ' ') {
                String str = new String(chars, left, i - left);
                list.add(str);
                left = i + 1;
            }
            if (val == ' ' && last == ' ') {
                left += 1;
            }
            last = val;
        }
        int remaining = chars.length - left;
        if (remaining > 0) {
            list.add(new String(chars, left, remaining));
        }
        StringBuilder builder = new StringBuilder();
        for (int i = list.size() - 1; i >= 0; i--) {
            if (i == 0) {
                builder.append(list.get(i));
            } else {
                builder.append(list.get(i)).append(" ");
            }
        }
        //去除先后空格
        String resStr = builder.toString();
        return resStr.trim();
    }
}
